package com.zhuangjie.rabbit.config.wrap;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Data
public class ExchangeWrap {
    private Exchange exchange;
    private List<QueueWrap> queueWraps = new ArrayList<>();

    private Consumer<Consumer<ExchangeWrap>> exchangeRegisterRequest;

    @Data
    @AllArgsConstructor
    public class QueueWrap {
        private String routeKey;
        private Queue queue;
    }

    public <T extends Exchange> ExchangeWrap(T exchange) {
        this.exchange = exchange;
    }

    public ExchangeWrap to(String routeKey, Queue queue) {
        QueueWrap queueWrap = new QueueWrap(routeKey, queue);
        queueWraps.add(queueWrap);
        return this;
    }

    public ExchangeWrap to(String routeKey, Queue queue, long delayTime) {
        String delayExchangeName = "dlx_" + queue.getName().replaceAll("_queue","") + "_exchange";
        exchangeRegisterRequest = (register)->
            register.accept(new ExchangeWrap(ExchangeBuilder.topicExchange(delayExchangeName).durable(true).build())
                    .to(routeKey, queue));

        Queue _queue = QueueBuilder.durable("_"+queue.getName()).ttl((int)delayTime)
                .deadLetterExchange(delayExchangeName)
                .deadLetterRoutingKey(routeKey)
                .build();
        return to(routeKey, _queue);
    }

}

